import pyglet, game, sys, time, antPickel
from antGP import *

SCALE = 20

ant_up_img = pyglet.image.load('ant_up_20.png')
ant_right_img = pyglet.image.load('ant_right_20.png')
ant_down_img = pyglet.image.load('ant_down_20.png')
ant_left_img = pyglet.image.load('ant_left_20.png')
cookie = pyglet.image.load('cookie_20.png')

def get_image(ch):
    if ch == 'A':
        return ant_up_img
    elif ch == '>':
        return ant_right_img
    elif ch == 'V':
        return ant_down_img
    elif ch == '<':
        return ant_left_img
    elif ch == 'o':
        return cookie
    else:
        raise Exception('Unknown ant direction')

def index_to_coord(idx):
    return idx % game.SIDE * SCALE, (game.SIDE * game.SIDE -1  - idx) / game.SIDE * SCALE

def quad(x1, y1, x2, y2):
    pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', (x1, y1, x1, y2, x2, y2, x2, y1)))

def line(x1, y1, x2, y2):
    pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2f', (x1, y1, x2, y2)))

def rect(x1, y1, x2, y2):
    line(x1, y1, x1, y2)
    line(x1, y2, x2, y2)
    line(x2, y2, x2, y1)
    line(x2, y1, x1, y1)

def grid():
    for i in range(game.SIDE * game.SIDE):
        x1 = ((i%game.SIDE)*SCALE)+1
        y1 = ((i/game.SIDE)*SCALE)+1
        x2 = x1 + SCALE+1
        y2 = y1 + SCALE+1
        rect(x1, y1, x2, y2)

def draw_ants(board):
    for i in range(game.SIDE):
        for j in range(game.SIDE):
            o = board.board[i][j]
            if type(o) == game.Ant:
                img = get_image(o.direction)
                ant = pyglet.sprite.Sprite(get_image(o.direction), j * SCALE, i * SCALE)
                ant.scale = float(SCALE) / float(img.width)
                ant.draw()
            if type(o) == game.Morsel:
                m = pyglet.sprite.Sprite(cookie, j * SCALE, i * SCALE)
                m.scale = float(SCALE) / float(cookie.width)
                m.draw()

if __name__ == '__main__':
    ant_problem = AntGP()
    ant_problem.run_ga(1)
    best_chromosome = ant_problem.best_individual()
    #best_chromosome = antPickel.unpickle_chromosome('besto.chrm')[0]
    boards = get_boards_for_chromosome(best_chromosome)
    i = 0
    window = pyglet.window.Window(width=(game.SIDE*SCALE+2), height=(game.SIDE*SCALE+2))
    @window.event
    def on_draw():
        print i
        print boards[i]
        window.clear()
        draw_ants(boards[i])
    def update(secs):
        global i
        i += 1
    pyglet.gl.glClearColor(230.0/255.0, 180.0/255.0, 130.0/255.0, 1)
    pyglet.clock.schedule_interval(update, 0.5)
    pyglet.app.run()













